import React, { useReducer } from "react";
import { useContext } from "react";

const initialState = 0;
const reducer = (state, action) => {
    switch (action.type) {
        case 'increment':
            return state + 1;

        case 'decrement':
            return state - 1;

        case 'reset':
            return action.count;
    
        default:
            return 0;
    }
};
const CountContext = React.createContext();
const CountProvider = ({children}) => {
    const contextValue = useReducer(reducer, initialState);
    return (
        <CountContext.Provider value={contextValue}>
            {children}
        </CountContext.Provider>
    )
}

const useCount = () => {
    const contextValue = useContext(CountContext);
    return contextValue;
}

const Counter = () => {
    const [count, dispatch] = useCount();
    return (
        <div>
            {count}
            <button onClick={ () => dispatch({ type: 'increment' }) }>add</button>
            <button onClick={() => dispatch({ type: 'decrement' })}>minus</button>
            <button onClick={() => dispatch({ type: 'reset', count: 0 })}>reset</button>
        </div>
    )
}

const Demo = () => (
    <div className="border">
        <p className="title">Demo--useReducer--4</p>  
        <CountProvider>
            <Counter></Counter>
        </CountProvider>
        <CountProvider>
            <Counter></Counter>
        </CountProvider>
    </div>
)

export default Demo;